<template>
  <div class="center">
    <div class="flex-center">
      <div class="flex-column">
        <draggable v-model="echartsList" group="echartsList" item-key="echartsType" class="flex-center-L" @end="ends">
          <template #item="{ element }">
            <div class="echarts-center" :key="element.echartsType">
              <div v-if="element.echartsType !== 'table'" class="echarts-demo card-box"></div>
              <div v-if="element.echartsType == 'table'" class="table-demo card-box">
                <el-table :data="state.tableData.data"
                          v-loading="state.tableData.loading"
                          stripe
                          border>
                  <el-table-column v-for="column in state.tableData.header" :min-width="column.width" align="center"
                                   :key="column.column" :label="column.columnName" :prop="column.column">
                    <el-table-column v-if="column.children?.length > 0" v-for="(item,index) in column.children"
                                     align="center"
                                     :min-width="item.width" :key="index" :label="item.columnName"
                                     :prop="item.column"></el-table-column>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </template>
        </draggable>
      </div>
      <div class="flex-center-R">
        <div style="display: flex;justify-content: flex-end;width: 100%;margin-bottom: 10px;">
          <el-button type="primary" @click="submit" style="justify-content: flex-end;">保存</el-button>
        </div>

        <draggable v-model="echartsDraggable" group="echartsList" item-key="echartsType" @end="handleDragEnd"
                   class="drag-center">
          <template #item="{ element, index }">
            <div
                class="echarts-center"
                :class="{ 'echarts-center-color': indexEcharts === index }"
                @click="indexEcharts = index"
                :key="element.echartsType"
            >
              <div v-if="element.echartsType !== 'table'" class="echarts-demo-clone card-box"></div>
              <div v-if="element.echartsType == 'table'" class="table-clone card-box">
                <el-table :data="state.tableData.data"
                          v-loading="state.tableData.loading"
                          stripe
                          border>
                  <el-table-column v-for="column in state.tableData.header"  :min-width="column.width" align="center" :key="column.column" :label="column.columnName" :prop="column.column">
                    <el-table-column  v-if="column.children?.length > 0" v-for="(item,index) in column.children" align="center" :min-width="item.width" :key="index" :label="item.columnName" :prop="item.column"></el-table-column>
                  </el-table-column>
                </el-table>
              </div>
              <div class="echarts-button" v-if="indexEcharts === index">
                <el-button type="primary" icon="el-icon-edit" circle @click="edit(index)"></el-button>
                <el-button type="danger" icon="el-icon-delete" circle @click="deleteData(index)"></el-button>
              </div>
            </div>
          </template>
        </draggable>
      </div>
    </div>

  </div>
</template>

<script setup>
import {ref, nextTick, onMounted} from 'vue';
import draggable from 'vuedraggable';
import VChart from 'vue-echarts';
import * as echarts from 'echarts/core';
import {LineChart, BarChart} from 'echarts/charts';
import RecursiveTableHeader from "@/components/RecursiveTableHeader";

/**
 * 定义表头属性映射关系
 */
const property = {
  prop: "column",
  label: "columnName",
  width: "width",
  children: "children",
};

// 处理拖拽结束事件
const handleDragEnd = () => {
  console.log("右侧拖拽结束事件");

  nextTick(() => {
    // const charts = document.querySelectorAll('.echarts-demo-clone');
    // charts.forEach(chart => {
    //   chart.__echarts__ && chart.__echarts__.resize();
    // });
    init();
  });
};

const echartsList = ref([
  {echartsType: 'line'},
  {echartsType: 'bar'},
  {echartsType: 'pie'},
  {echartsType: 'table'}
]);
const state = reactive({
  tableData: {
    loading: false,
    header: [
      {
        column: "dim1",
        columnName: "堆型",
        width: "100px",
        children: [],
      },
      {
        column: "dim3",
        columnName: "机组寿命",
        width: "100px",
        children: [],
      },
      {
        column: "dim4",
        columnName: "装机成本",
        width: "100px",
        children: [],
      },
      {
        column: "2030",
        columnName: "2030年",
        width: "560px",
        children: [
          {
            column: "kf12030",
            columnName: "核电装机容量(亿千瓦)",
            width: "280px",
            children: [],
          }
        ],
      }, {
        column: "2040",
        columnName: "2040年",
        width: "560px",
        children: [
          {
            column: "kf12040",
            columnName: "核电装机容量(亿千瓦)",
            width: "280px",
            children: [],
          }
        ],
      }, {
        column: "2050",
        columnName: "2050年",
        width: "560px",
        children: [
          {
            column: "kf12050",
            columnName: "核电装机容量(亿千瓦)",
            width: "280px",
            children: [],
          }
        ],
      }, {
        column: "2060",
        columnName: "2060年",
        width: "560px",
        children: [
          {
            column: "kf12060",
            columnName: "核电装机容量(亿千瓦)",
            width: "280px",
            children: [],
          }
        ],
      }

    ],
    data: [{
      dim1: '二代及三代大堆',
      dim3: '60年',
      dim4: '200亿',
      kf12030: '1.08',
      kf12040: '0.00',
      kf12050: '0.01',
      kf12060: '0.01'
    }, {
      dim1: '三代小堆',
      dim3: '60年',
      dim4: '400亿',
      kf12030: '2.46',
      kf12040: '0.02',
      kf12050: '0.01',
      kf12060: '0.01'
    }, {
      dim1: '四代堆（高温堆）',
      dim3: '40年',
      dim4: '100亿',
      kf12030: '3.23',
      kf12040: '0.18',
      kf12050: '0.74',
      kf12060: '0.01'
    }, {
      dim1: '四代堆（快堆）',
      dim3: '30年',
      dim4: '80亿',
      kf12030: '3.23',
      kf12040: '0.18',
      kf12050: '1.17',
      kf12060: '0.01'
    }]
  }
});
const echartsDraggable = ref([]);
const myChart = ref(null);
const myChartClone = ref(null);
const indexEcharts = ref(null);
const charData = ref({});
const init = () => {
  const doms = document.querySelectorAll('.echarts-demo');
  Array.from(doms).forEach((x, index) => {
    const echartsType = echartsList.value[index].echartsType;
    if (echartsType != 'table') {
      if (echartsType === 'bar') {
        charData.value = chartOptions.value;
      } else if (echartsType === 'line') {
        charData.value = chartLineOptions2.value;
      } else if (echartsType === 'pie') {
        charData.value = pieOptions.value;
      }

      myChart.value = echarts.init(x);
      myChart.value.setOption(charData.value);
    }
  });
};

const ends = (e) => {
  console.log("111111111111");
  echartsDraggable.value = echartsDraggable.value.map(x => JSON.parse(JSON.stringify(x)));
  nextTick(() => {
    draggableEcharts(e.oldIndex, e.newIndex);
  });
};

const draggableEcharts = (oldIndex, newIndex) => {
  const doms = document.querySelectorAll('.echarts-demo-clone');
  Array.from(doms).forEach((x, index) => {
    console.log('index:' + index);
    const echartsType = echartsDraggable.value[index].echartsType;
    console.log("echartsType:" + echartsType);
    if (echartsType != 'table') {
      if (echartsType === 'bar') {
        charData.value = chartOptions.value;
      } else if (echartsType === 'line') {
        charData.value = chartLineOptions2.value;
      } else if (echartsType === 'pie') {
        charData.value = pieOptions.value;
      }

      myChartClone.value = echarts.init(x);
      myChartClone.value.setOption(charData.value);
    }

  });
};

/**
 * 柱状图
 * @type {Ref<UnwrapRef<{yAxis: {type: string}, xAxis: {data: string[], type: string}, legend: {data: string[]}, series: [{data: number[], name: string, type: string},{data: number[], name: string, type: string}], tooltip: {axisPointer: {type: string}, trigger: string}, title: {text: string}}>>}
 */
const chartOptions = ref({
  title: {
    text: '发电量预测',
    left: 'center'
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  // legend: {
  //   data: ['中长期仅新建四代堆-核能发电量（万亿千瓦时）', '中长期新建三代和四代堆-核能发电量（万亿千瓦时）'],
  //   right: 'right'
  // },
  xAxis: {
    type: 'category',
    data: ['2030', '2040', '2050', '2060']
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: '中长期仅新建四代堆-核能发电量（万亿千瓦时）',
      type: 'bar',
      data: [0.89, 1.96, 3.16, 3.44]
    },
    {
      name: '中长期新建三代和四代堆-核能发电量（万亿千瓦时）',
      type: 'bar',
      data: [0.89, 1.99, 3.24, 3.53]
    }
  ]
});
/**
 * 饼图
 * @type {Ref<UnwrapRef<{series: [{data: [{name: string, value: number},{name: string, value: number},{name: string, value: number},{name: string, value: number},{name: string, value: number},null,null,null], name: string, emphasis: {itemStyle: {shadowOffsetX: number, shadowBlur: number, shadowColor: string}}, type: string, radius: string}], tooltip: {trigger: string}, title: {left: string, text: string}}>>}
 */
const pieOptions = ref({
  title: {
    text: '核能供汽量占比',
    left: 'center'
  },
  tooltip: {
    trigger: 'item'
  },
  series: [
    {
      name: '核能供汽量占比',
      type: 'pie',
      radius: '50%',
      data: [
        {value: 0.88, name: '2030年-中长期仅新建四代堆-供汽量占比'},
        {value: 5.01, name: '2040年-中长期仅新建四代堆-供汽量占比'},
        {value: 10.05, name: '2050年-中长期仅新建四代堆-供汽量占比'},
        {value: 13.56, name: '2060年-中长期仅新建四代堆-供汽量占比'},
        {value: 0.88, name: '2030年-中长期新建三代和四代堆-供汽量占比'},
        {value: 6.06, name: '2040年-中长期新建三代和四代堆-供汽量占比'},
        {value: 12.26, name: '2050年-中长期新建三代和四代堆-供汽量占比'},
        {value: 16.16, name: '2060年-中长期新建三代和四代堆-供汽量占比'}
      ],
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }
  ]
});

/**
 * 折线图
 * @type {Ref<UnwrapRef<{yAxis: {type: string}, xAxis: {data: string[], type: string, boundaryGap: boolean}, legend: {data: string[]}, series: [{stack: string, data: number[], name: string, type: string},{stack: string, data: number[], name: string, type: string}], tooltip: {trigger: string}, title: {text: string}}>>}
 */
const chartLineOptions2 = ref({
  title: {
    text: '核能供汽量',
    left: 'center'
  },
  tooltip: {
    trigger: 'axis'
  },
  // legend: {
  //   data: ['中长期仅新建四代堆-核能供汽量（万吨标煤）', '中长期新建三代和四代堆-核能供汽量（万吨标煤）'],
  //   right: 'right'
  // },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: ['2030', '2040', '2050', '2060']
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: '中长期仅新建四代堆-核能供汽量（万吨标煤）',
      type: 'line',
      stack: '中长期仅新建四代堆-核能供汽量（万吨标煤）',
      data: [370, 1507, 2041, 2253]
    },
    {
      name: '中长期新建三代和四代堆-核能供汽量（万吨标煤）',
      type: 'line',
      stack: '中长期新建三代和四代堆-核能供汽量（万吨标煤）',
      data: [370, 1825, 2489, 2685]
    }
  ]
});


const deleteData = (index) => {
  echartsDraggable.value.splice(index, 1);
};

onMounted(() => {
  init();
  window.onresize = () => {
    if (myChart.value) myChart.value.resize();
    if (myChartClone.value) myChartClone.value.resize();
  };
});

</script>

<style scoped lang="less">
.center {
  width: 100%;
  height: 900px; /* Set the height to 900px */

  .flex-center {
    display: flex;
    width: 100%;
    height: 100%;

    .flex-column {
      margin-top: 3%;
      width: 20%;
      height: 100%;
      display: flex;
      border: 1px solid pink;
      overflow-y: auto; /* 添加竖向滚动条 */
      flex-direction: column;
      margin-left: 5px;

      .flex-center-L {
        width: 100%;
        height: 100%;
      }

      .echarts-center {
        width: 100%;
        height: 30%;
        border: 1px solid #126fcc;

        .table-demo {
          width: 100%;
          height: 100%;
        }

        .echarts-demo {
          width: 100%;
          height: 100%;
        }
      }
    }

    .flex-center-R {
      width: 80%;
      height: 100%;
      display: flex;
      flex-wrap: wrap;
      padding: 12px;
      margin-left: 12px;

      .drag-center {
        width: 100%;
        height: 100%;
        border: 1px solid pink;
        box-shadow: 0px 0px 6px 6px rgba(183, 183, 183, 0.28);
        display: flex;
        flex-wrap: wrap;

        .echarts-center {
          width: 45%;
          height: 45%;
          border: 1px solid #126fcc;
          margin: 1rem 1.5rem 1rem;
          position: relative;


          .table-clone {
            width: 100%;
            height: 100%;
          }

          .echarts-demo-clone {
            width: 100%;
            height: 100%;
          }

          .echarts-button {
            position: absolute;
            left: 0;
            top: 0;
          }
        }

        .echarts-center-color {
          border: 1px solid red;
        }
      }


    }
  }

  .form-item-center {
    display: flex;

    ::v-deep .el-form-item {
      width: 50%;
    }
  }

  ::v-deep .el-dialog__footer {
    text-align: center;
  }
}

.card-box {
  padding: 1rem;
  box-shadow: 0px 0px 6px 6px rgba(183, 183, 183, 0.28);
  //margin: 0 1.5rem 1rem;
  border-radius: 4px;
  background-color: rgba(83, 168, 255, 0.28);
}
</style>